package com.component.api.model.dto;

import cn.hutool.core.util.StrUtil;
import com.component.api.function.OperationFunction;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.script.*;
import java.io.Serializable;

/**
 * 描述：
 * 统一输出列
 * @author xianggj
 * @Date 2021/11/29 14:11
 **/
@Data
@NoArgsConstructor
public class UnifieldColumnDTO extends ColumnDTO implements Serializable {
    private static final long serialVersionUID = -1L;

    /**
     * 统一输出规则
     */
    private String rule;


    /**
     * 获取计算公式
     * 放大10倍、放大100倍、放大1000倍、放大1万倍、放大10万倍、放大100万倍、放大1000万倍、缩小10倍、缩小100倍、缩小1000倍、缩小1万倍、缩小10万倍、缩小100万倍、缩小1000万倍
     * @return
     */
    public OperationFunction getFunction(){
        if (rule == null) {
            return e -> e;
        }
        switch (rule){
            case "放大10倍":
                return e-> e * 10;
            case "放大100倍":
                return e-> e * 100;
            case "放大1000倍":
                return e-> e * 1000;
            case "放大1万倍":
                return e-> e * 10000;
            case "放大10万倍":
                return e-> e * 100000;
            case "放大100万倍":
                return e-> e * 1000000;
            case "放大1000万倍":
                return e-> e * 10000000;
            case "缩小10倍":
                return e-> e / 10;
            case "缩小100倍":
                return e-> e / 100;
            case "缩小1000倍":
                return e-> e / 1000;
            case "缩小1万倍":
                return e-> e / 10000;
            case "缩小10万倍":
                return e-> e / 100000;
            case "缩小100万倍":
                return e-> e / 1000000;
            case "缩小1000万倍":
                return e-> e / 10000000;
            default:
                //这里变成公式了
                rule = StrUtil.replace(rule, "%%", "F");
                rule = StrUtil.replace(rule, "×", "*");
                rule = StrUtil.replace(rule, "÷", "/");
                rule = StrUtil.replace(rule, "x", "*");
                rule = StrUtil.replace(rule, "X", "*");
                return e-> {
                    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
                    Compilable compilable = (Compilable) engine;
                    Bindings bindings = engine.createBindings(); //Local级别的Binding
                    CompiledScript JSFunction = null; //解析编译脚本函数
                    try {
                        JSFunction = compilable.compile(rule);
                        bindings.put("F", e);
                        return Double.valueOf(JSFunction.eval(bindings).toString());
                    } catch (ScriptException ex) {
                        ex.printStackTrace();
                    }
                    return e;
                };
        }
    }


}
